package com.sanji.register.controller;/**
 * Created by 杨其才 on 2017/5/14.
 *
 * @
 */

import com.sanji.register.UserService;
import com.sanji.register.model.User;
import com.sanji.register.repository.UserRepository;
import com.sanji.util.ResponseFactory;
import com.sun.javafx.collections.MappingChange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author yangqc
 *         User: yangqc
 *         Date: 2017/5/14
 *         Time: 10:14
 * @description
 * @since 1.0
 */
@RestController
public class RegisterController {
	@Autowired
	private UserRepository userRepository;

	@Autowired
	private UserService userService;

	private Logger logger = LoggerFactory.getLogger(RegisterController.class);

	@RequestMapping(value = "/", method = RequestMethod.POST)
	public ResponseFactory.HttpResponse register(@RequestBody User user) {
		try {
			user = userRepository.save(user);
			user.setPassword("*****");

			return ResponseFactory.getSuccussed(user);
		} catch (Exception e) {
			logger.debug("注册用户失败", e);
			return ResponseFactory.getFailed(e.getMessage());
		}
	}

	@RequestMapping("/checkPhone/{phone}")
	public ResponseFactory.HttpResponse checkPhone(@PathVariable String phone) {
		try {
			int num = userRepository.countByPhone(phone);
			return num == 0 ? ResponseFactory.getSuccussed(true) : ResponseFactory.getSuccussed(false);
		} catch (Exception e) {
			logger.debug("校验手机号码失败", e);
			return ResponseFactory.getFailed(e.toString());
		}
	}

	@RequestMapping("/checkName/{name}")
	public ResponseFactory.HttpResponse checkName(@PathVariable String name) {
		try {
			int num = userRepository.countByName(name);
			return num == 0 ? ResponseFactory.getSuccussed(true) : ResponseFactory.getSuccussed(false);
		} catch (Exception e) {
			logger.debug("校验用户名失败", e);
			return ResponseFactory.getFailed(e.toString());
		}
	}
	@RequestMapping(value = "/modifyInfo/{userId}", method = RequestMethod.POST)
	public ResponseFactory.HttpResponse modifyInfo(@PathVariable String userId, @RequestBody Map<String, String> reqMap) {
		try {
			userService.modifyUser(userId, reqMap);
			return ResponseFactory.getSuccussed(true);
		} catch (Exception e) {
			logger.debug("修改认证信息失败", e);
			return ResponseFactory.getFailed(e.toString());
		}
	}
}
